import json

from bson.objectid import ObjectId

from api_base import *
from docker_client import *


class APIImageHandler(APIBaseHandler):
    OPTIONAL_FIELDS = ['']

    @check_role(RoleTeacher)
    async def get(self):
        '''
        镜像列表
        '''
        skip = 0
        limit = 0
        try:
            skip = int(self.get_argument('skip'))
            limit = int(self.get_argument('limit'))
        except:
            pass
        images = []
        async for item in self.db.images.find({}).limit(limit).skip(skip):
            item.pop('_id')
            images.append(item)
        self.write_json(images)

    @check_role(RoleAdmin)
    async def post(self):
        '''
        添加删除镜像
        '''
        try:
            js = json.loads(self.request.body)
            op = js['op']
            image = js['image']
            to_operate = {'image': image}
            if op == 'add':
                to_operate.update({'command': js['command']})
                to_operate.update(
                    {k: js[k] for k in js.keys() if k in self.OPTIONAL_FIELDS})
        except:
            self.write_json({'info': 'json_error'})
            return
        if op == 'add':
            # TODO check image
            res = await self.db.images.insert_one(to_operate)
            self.write_json({'info': 'ok'})
        elif op == 'del':
            res = await self.db.images.delete_one(to_operate)
            self.write_json({'info': 'ok',
                             'deleted': res.deleted_count})
        else:
            self.write_json({'info': 'unknown op'})
